<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'resetpwd', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * @ApiTitle    (用户登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="account", type="string", required=true, description="账号", sample="")
     * @ApiParams   (name="password", type="string", required=true, description="密码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn   ({
    "code": 1,
    "msg": "登录成功",
    "time": "1571380050",
    "data": {
    "user_info": {
    "id": 18,
    "username": "18911621396",
    "nickname": "zhenzh",
    "mobile": "18911621396",
    "avatar": "/uploads/20191018/8284af499ea84f5bb8517c815867e7c3.jpg",
    "score": 0,
    "token": "51f8cd8e-9efc-479b-9cc7-4db32ab6b15c",
    "user_id": 18,
    "createtime": 1571380051,
    "expiretime": 1573972051,
    "expires_in": 2592000
    }
    }
    })
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiTitle    (注销登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/logout)
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "注销成功",
    "time": "1564640159",
    "data": null
    })
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * @ApiTitle    (修改用户个人信息)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/editProfile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="username", type="string", required=false, description="用户名", sample="")
     * @ApiParams   (name="nickname", type="string", required=false, description="昵称", sample="")
     * @ApiParams   (name="birthday", type="string", required=false, description="生日", sample="")
     * @ApiParams   (name="avatar", type="string", required=false, description="头像地址", sample="")
     * @ApiParams   (name="bio", type="string", required=false, description="个人简介", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function editProfile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * @ApiTitle    (修改学校)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2020/3/5 10:27)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/editSchool)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function editSchool()
    {
        $school_id = $this->request->request('school_id');
        $user = $this->auth->getUser();

        $school = \app\common\model\School::where('id', $school_id)->find();
        if (!$school) {
            $this->error('学校不存在');
        }

        $user->school_id = $school_id;
        $user->save();
        $this->success();
    }

    /**
     * @ApiTitle    (修改密码)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/changePwd)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=false, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=false, description="验证码", sample="")
     * @ApiParams   (name="password", type="string", required=false, description="新密码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1564640159",
    "data": null
    })
     */
    public function changePwd()
    {
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $captcha = $this->request->request('captcha');

        $user = $this->auth->getUser();

        if (!$mobile || !$captcha || !$password) $this->error(__('Invalid parameters'));
        if (!Validate::regex($mobile, "^1\d{10}$")) $this->error(__('Mobile is incorrect'));
        if ($mobile != $user['mobile']) $this->error(__('手机号不正确'));

        $ret = Sms::check($mobile, $captcha, 'changePwd');
        if (!$ret) $this->error(__('Captcha is incorrect'));
        Sms::flush($mobile, 'changePwd');

        $ret = $this->auth->changepwd($password, '', true);

        if ($ret) {
            $this->success(__('密码修改成功'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiTitle    (绑定手机号)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/7/31 10:49)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/bindMobile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "绑定成功",
    "time": "1564542858",
    "data": null
    })
     */
    public function bindMobile()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');

        if (!$mobile || !$captcha)
            $this->error(__('Invalid parameters'));

        if (!Validate::regex($mobile, "^1\d{10}$"))
            $this->error(__('Mobile is incorrect'));

        if (!Sms::check($mobile, $captcha, 'bindMobile'))
            $this->error(__('Captcha is incorrect'));

        $user = $this->auth->getUser();
        if ($user['mobile']) {
            $this->error(__('您已经绑定过手机号了'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->count()) {
            $this->error(__('手机号已经被绑定'));
        }

        $user->mobile = $mobile;
        $result = $user->save();

        if ($result)
            $this->success(__('绑定成功'));
        else
            $this->error(__('绑定失败'));
    }

    /**
     * @ApiTitle    (手机号登录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/mobilelogin)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "登录成功",
    "time": "1571379388",
    "data": {
    "user_info": {
    "id": 18,
    "username": "18911621396",
    "nickname": "zhenzh",
    "mobile": "18911621396",
    "avatar": "/uploads/20191018/8284af499ea84f5bb8517c815867e7c3.jpg",
    "score": 0,
    "token": "805999b5-4d42-4352-8813-df4a4e375a7c",
    "user_id": 18,
    "createtime": 1571379389,
    "expiretime": 1573971389,
    "expires_in": 2592000
    }
    }
    })
     */
    public function mobileLogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobileLogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);

            if ($ret) {
                Sms::flush($mobile, 'mobileLogin');
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }

        } else {
            $this->error('手机号不存在');
        }

    }

    /**
     * @ApiTitle    (修改手机号)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/changemobile)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1571380798",
    "data": null
    })
     */
    public function changeMobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changeMobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;

        if ($user->save()) {
            Sms::flush($mobile, 'changeMobile');
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }

    }

    /**
     * 第三方登录
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request("platform");
        $code = $this->request->request("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * @ApiTitle    (重置密码)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/10/18 10:27)
     * @ApiSummary  (描述)
     * @ApiBody  (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/resetpwd)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号", sample="")
     * @ApiParams   (name="password", type="string", required=true, description="新密码", sample="")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "重置密码成功",
    "time": "1571380038",
    "data": null
    })
     */
    public function resetPwd()
    {
        $mobile = $this->request->request("mobile");
        $password = $this->request->request("password");
        $captcha = $this->request->request("captcha");
        if (!$password || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetPwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetPwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($password, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function teacher()
    {
        $user_id = $this->auth->id;

        $teacher = \app\common\model\Teacher::where('user_id', $user_id)->find();

        $this->success('', $teacher);
    }

    public function classes()
    {
        $user_id = $this->auth->id;

        $teacher = \app\common\model\Teacher::where('user_id', $user_id)->find();

        $classes = [];

        if ($teacher) {
            $classes = \app\common\model\Classes::where('headmaster', $teacher->id)->find();
        } else {
            $student = \app\common\model\Student::where('user_id', $user_id)->find();
            if ($student) {
                $classes = \app\common\model\Classes::where('id', $student->class_id)->find();
            }
        }

        $this->success('', $classes);
    }

    public function school()
    {
        $user_id = $this->auth->id;

        $rule = [];
        if ($this->auth->school_id) {
            $school_id = $this->auth->school_id;
            $teacher = \app\common\model\Teacher::where('user_id', $user_id)
                ->where('school_id', $school_id)
                ->field('id')
                ->find();
            if ($teacher) {
                $rule['name'] = 'teacher';
                $rule['id'] = $teacher->id;
            } else {
                $student = \app\common\model\Student::where('user_id', $user_id)
                    ->where('school_id', $school_id)
                    ->field('id')
                    ->find();
                if ($student) {
                    $rule['name'] = 'student';
                    $rule['id'] = $student->id;
                }
            }
        } else {
            $teacher = \app\common\model\Teacher::where('user_id', $user_id)->find();
            if ($teacher) {
                $school_id = $teacher->school_id;
                $rule['name'] = 'teacher';
                $rule['id'] = $teacher->id;
            } else {
                $student = \app\common\model\Student::where('user_id', $user_id)->find();
                if ($student) {
                    $classes = \app\common\model\Classes::where('id', $student->class_id)->find();
                    if ($classes) {
                        $school_id = $classes->school_id;
                        $rule['name'] = 'student';
                        $rule['id'] = $student->id;
                    }
                }
            }
        }

        if (isset($school_id)) {
            $school = \app\common\model\School::where('id', $school_id)
                ->withCount(['classes', 'student', 'teacher'])
                ->find();

            if ($rule) {
                $school['role_id'] = $rule['id'];
                $school['role_name'] = $rule['name'];
            }

            $this->success('', $school);
        }

        $this->error('');
    }

}
